/*
 * =====================================================================================
 *
 *       Filename: main.c 
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  08/28/12 17:20:17
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Andyli (gk), andy.y.li@163
 *        Company:  gl
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <errno.h>
#include "socklib.h"

const int MAX_LEN = 1024;

int main(int argc,char *argv[])
{
	unsigned short port = 1496;
	int server_id,client_id;
	fd_set readfds,tmpfds;

	if (argc > 1){
		port = atoi(argv[1]);	
	}
	server_id = make_server_socket(port);
	if (server_id == -1){
		fprintf(stderr,"make server error: %s\n",strerror(errno));
		return -1;
	}

	FD_ZERO(&readfds);
	FD_SET(server_id,&readfds);

	while(1) {
		int fd;
		int client_len;
		int nread;
		struct sockaddr_in client_address;
		struct timeval timeout;
		timeout.tv_sec = 0;
		timeout.tv_usec = 100000; // 100ms

		tmpfds = readfds;
		int reval = select(FD_SETSIZE,&tmpfds,(fd_set *)0,
				(fd_set *)0,&timeout);
		if (reval == -1){
			fprintf(stderr,"select error: %s\n",strerror(errno));
			return -1;
		}
		
		for (fd = 0;fd < FD_SETSIZE;fd++){
			if (FD_ISSET(fd,&tmpfds)){
				if (fd == server_id){
					client_len = sizeof(struct sockaddr_in);
					client_id = accept(server_id,
							(struct sockaddr *)&client_address,&client_len);
					FD_SET(client_id,&readfds);
				}
				else {
					ioctl(fd,FIONREAD,&nread);
					if (nread == 0){
						close(fd);
						FD_CLR(fd,&readfds);
					}
					else{
						char buf[MAX_LEN];
						int n;
						memset(buf,0,MAX_LEN);
						n = read(fd,buf,MAX_LEN);
						if (n){
							buf[n] = '\0';
							printf("get data from client: %s\n",buf);
							//sleep(5);
						//	write(fd,"Reply: ",7);
							write(fd,buf,strlen(buf));
						}
					}
				}
			}

		}

	}

	return 0;
}



